//
//  ToolVideo.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import UIKit
import Photos

public class VideoManager {
    
    public static var shared  = VideoManager()
    // 当前控制器
    private var currentVc: UIViewController?
    private var resultBlock: BlockSingleBool?
    private var action:  UIAlertController?
    private var videoPath: String = ""
   
    // 保存视频
    public func saveFileVideo( _ videoPath:String, _ currentVc:UIViewController , _ resultBlock: @escaping BlockSingleBool){
        self.resultBlock = resultBlock
        self.currentVc = currentVc
        self.videoPath = videoPath
        permissions()
    }
    
    
    ///有没有pn写入s权限判断
    private func permissions(_ int: Int = 0){
        if PHPhotoLibrary.authorizationStatus().rawValue == PHAuthorizationStatus.notDetermined.rawValue {
            // 用户还没做选择
            PHPhotoLibrary.requestAuthorization({ (status) in
                if status.rawValue == PHAuthorizationStatus.authorized.rawValue {
                    // Print.log("点同意")
                    self.save()
                } else if status == PHAuthorizationStatus.denied ||  status == PHAuthorizationStatus.restricted {
                    // Print.log("点拒绝")
                    self.jumpSet(str: "相册")
                }
            })
        } else if(PHPhotoLibrary.authorizationStatus().rawValue == PHAuthorizationStatus.authorized.rawValue ) {
            // 用户同意写入权限
            print(PHPhotoLibrary.authorizationStatus().rawValue)
            self.save()
        }else{
            self.jumpSet(str: "相册")
        }
    }
     
    // 保存视频
    private func save(){
        if(videoPath.count < 10){
            resultBlock?(false)
            videoPath = ""
            resultBlock = nil
        } else {
            PHPhotoLibrary.shared().performChanges({
                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(string: self.videoPath)!)
            }) { [weak self](success, error) in
                if !success { Log_y.print_("视频保存失败：\(error?.localizedDescription ?? "")") }
                self?.resultBlock?(success)
                self?.videoPath = ""
                self?.resultBlock = nil
            }
        }
    }
    
    // 跳转到设置中开启权限
    private func jumpSet(str: String){
        action = UIAlertController(title: "提示", message: "请在在设置中打开app的\(str)权限", preferredStyle: UIAlertController.Style.alert)
        let action1 = UIAlertAction(title: "设置", style: UIAlertAction.Style.default) { actions in
            Tools.openSet(.mainSet)
        }
        let action2 = UIAlertAction(title: "取消", style: UIAlertAction.Style.cancel) { actions in }
        action?.addAction(action1)
        action?.addAction(action2)
        if action != nil {
            currentVc?.present(action!, animated: true, completion: nil)
        }
    }
}
